package com.yicun.ycprint

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import com.dantsu.escposprinter.EscPosCharsetEncoding
import com.dantsu.escposprinter.EscPosPrinter
import com.dantsu.escposprinter.connection.usb.UsbConnection
import com.dantsu.escposprinter.connection.usb.UsbPrintersConnections
import com.dantsu.escposprinter.textparser.PrinterTextParserImg
import com.hjq.toast.ToastUtils
import com.yicun.ycprint.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private val ACTION_USB_PERMISSION = "com.android.yicun.USB_PERMISSION"
    private lateinit var usbManager: UsbManager

    private lateinit var activityMainBinding: ActivityMainBinding

    private lateinit var printer: EscPosPrinter


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityMainBinding = ActivityMainBinding.inflate(LayoutInflater.from(this))
        setContentView(activityMainBinding.root)
        click()
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun click() {
        activityMainBinding.apply {
            btnConnect.setOnClickListener {
                printUsb()
            }
            btnClose.setOnClickListener {
                printer.disconnectPrinter()
            }
            btnNormalTxt.setOnClickListener {
                printer.printFormattedText("[L]this is normal txt\n")
            }
            btn2WTxt.setOnClickListener {
                printer.printFormattedText("[R]<font size='wide'>这是右对齐2倍宽度的文字这是右对齐2倍宽度的文字这是右对齐2倍宽度的文字这是右对齐2倍宽度的文字</font>\n")
            }
            btn2HTxt.setOnClickListener {
                printer.printFormattedText("[C]<font size='tall'>这是居中2倍高度的文字</font>\n")
            }
            btn2WHTxt.setOnClickListener {
                printer.printFormattedText("[L]<font size='big'>这是2倍宽高的文字</font>\n")
            }
            btnWhitetxtBlackBg.setOnClickListener {
                printer.printFormattedText("[L]<font color='black'>这是黑字白底</font><\n")
            }
            btnBlacktxtWhiteBg.setOnClickListener {
                printer.printFormattedText("[L]<font color='bg-black'>这是白字黑底</font>\n")
            }
            btnRedTxt.setOnClickListener {
                printer.printFormattedText("[L]<font color='red'>这是红字白底</font>\n")
            }

            btnBoldTxt.setOnClickListener {
                printer.printFormattedText("[L]<b>这是加粗文字</b>\n")
            }

            btnUnderline.setOnClickListener {
                printer.printFormattedText("文字下划线\n" + "------------")
            }
            btnImg.setOnClickListener {
                printer.printFormattedText(
                    "[L]<img>" + PrinterTextParserImg.bitmapToHexadecimalString(
                        printer,
                        resources.getDrawable(R.drawable.images)
                    ) + "</img>\n"
                )
            }
            btnBarCode.setOnClickListener {
                printer.printFormattedText("[C]<barcode type='ean13' height='10'>831254784551</barcode>\n")
            }
            btnQRCode.setOnClickListener {
                printer.printFormattedText("[C]<qrcode size='20'>http://www.biying.com/</qrcode>")
            }
        }

    }


    fun printUsb() {
        val usbConnection = UsbPrintersConnections.selectFirstConnected(this)
        val usbManager = this.getSystemService(USB_SERVICE) as UsbManager
        if (usbConnection != null) {
            val permissionIntent =
                PendingIntent.getBroadcast(this, 0, Intent(ACTION_USB_PERMISSION), 0)
            val filter = IntentFilter(ACTION_USB_PERMISSION)
            registerReceiver(usbReceiver, filter)
            usbManager.requestPermission(usbConnection.device, permissionIntent)
        }
    }

    private val usbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            val action = intent.action
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized(this) {
                    val usbDevice =
                        intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (usbDevice != null) {
                            usbManager =
                                getSystemService(Context.USB_SERVICE) as UsbManager
                            printer =
                                EscPosPrinter(
                                    UsbConnection(usbManager, usbDevice),
                                    203,
                                    58f,
                                    32, EscPosCharsetEncoding("gb2312", 128)
                                )
                            ToastUtils.show("打印机连接成功")
                        }
                    }

                }
            }
        }
    }
}